import 'dart:math';

import 'package:acgn_pioneer/public.dart';
import 'package:acgn_pioneer/widgets/reader/events/_index.dart';
import 'package:acgn_pioneer/widgets/reader/models/_reader_state.dart';
import 'package:event_bus/event_bus.dart';
import 'package:flutter/widgets.dart';

/// 图片预加载服务类
/// 
class ReaderImageLoaderService {
  static const String name = 'ImageLoader';

  /// 事件句柄
  EventBus bus;

  /// 阅读器仓库引用
  ReaderState state;

  ReaderImageLoaderService(this.state, this.bus);

  /// 同一时间加载队列长度
  final maxLen = 3;

  /// 是否加载图片中
  var runing = false;

  /// 当前图片请求队列
  var requestQueue = [];

  // 循环图片加载
  runImageLoad() {
    if (this.runing) {
      return;
    }
    this.runing = true;
    this.loadImageBatch();
  }

  // 加载图片
  loadImageBatch() {
    ///  获取没有初始化的|没有锁住的
    var imgs = state.chapterImageList.where((img) => !img.isInited).toList();
    if (imgs.length == 0) {
      // 艾玛，累死了，终于没有需要加载的图片了~
      this.runing = false;
      return;
    }
    if (this.requestQueue.length == this.maxLen) {
      // 加载队列达到上限，不在同步加载
      return;
    }
    imgs.sort((a, b) => b.priority - a.priority);
    var loadCount = min(this.maxLen - this.requestQueue.length, imgs.length);
    imgs.sublist(0, loadCount).forEach((img) => {this.requestImg(img)});
  }

  /// 请求图片
  requestImg(ChapterImageModel image) {
    if (image.priority == 0) {
      // LogUtil.v('预加载图片${image.index}/${image.chapterId}');
    }

    image.isInited = true;
    this.requestQueue.add(image);
    if (image.faileCount == 0) {}

    /// 模拟失败
    // image.originUrl =
    //     image.faileCount == 0 ? (image.originUrl + 'x') : image.originUrl;
    Image loadImg = Image.network(
      image.originUrl,
      headers: {'referer': 'http://www.zymk.cn/'},
    );
    loadImg.image
        .resolve(ImageConfiguration())
        .addListener(new ImageStreamListener((ImageInfo info, bool _) {
          image.originWidth = info.image.width.toDouble();
          image.originHeight = info.image.height.toDouble();
          image.isSucceed = true;
          image.dom = info;
          this.finishImgLoad(image);
        }, onError: (dynamic exception, StackTrace stackTrace) {
          image.faileCount += 1;
          this.finishImgLoad(image);
        }));
    // var a = CachedNetworkImage(
    //     imageUrl: image.originUrl,
    //     imageBuilder: (context, imageProvider) {
    //       image.isSucceed = true;
    //       getLocalImageInfo(imageProvider).then((value) {
    //         image.originWidth = value.image.width.toDouble();
    //         image.originWidth = value.image.height.toDouble();
    //         this.finishImgLoad(image);
    //       });
    //       return;
    //     },
    //     errorWidget: (context, url, error) {
    //       image.faileCount += 1;
    //       this.finishImgLoad(image);
    //       return;
    //     });
  }

  /// 请求图片完成
  finishImgLoad(ChapterImageModel image) {
    bus.fire(ReaderImageLoadEvent(image));
    this.updateRequestQueue(image);
    this.loadImageBatch();
  }

  /// 更新请求队列
  updateRequestQueue(image) {
    this.requestQueue.remove(image);
  }
}
